package compound.repository

import org.compass.core.engine.SearchEngineQueryParseException
import org.apache.lucene.search.BooleanQuery

import compound.repository.DataExportService
import compound.repository.SearchService
import util.ConvertInchi

class SearchController {

    /**
     * reference to the search services
     */
    SearchService searchService = null

    DataExportService dataExportService = new DataExportService();


    def index = {


        if (params.query != null) {
            return [query: params.query]
        }

    }

    def doTagSearch = {
        redirect(action: textSearch, params: ["query": params.selectedTag])

    }
    /**
     * search against the controller
     */
    def search = {

        //allows us to search over tag lists

        assert params.query != null, "you need to provide some a query in the params object"

        assert params.query instanceof String, "the query needs to be of type string"

        def result = searchService.searchGeneric(params.query, params)

        log.info "returend: ${result}"
        //forward to the controller
        return [result: result]
    }

    def molSearch = {
        String query = params.query

        String inchi = ConvertInchi.convertMolToInchi(query.trim())

        log.debug "received: ${inchi}"
        log.debug "mol was\n\n ${query}\n\n"

        if (inchi == null | inchi.length() == 0) {
            //we did not find an inchi file
            flash.message = "Error! it appears that your mol file was invalid. Please try again with a valid mol file!"
            redirect(controller: "homePage", action: "index")
        }
        else {
            //needed so we are able to use the index functions!
            def key = ConvertInchi.convertInchiToKey(inchi)

            redirect(action:textSearch,params:[query:key])
        }
    }
    /**
     * advanced search against the controller
     */
    def advancedSearch = {}

    /**
     * executes a text based search using lucene and compass
     */
    def textSearch = {

        if (params.query == null || params.query.toString().trim().length() == 0) {
            flash.message = "Error! Query parameter is mandatory, Please Enter Query."
            redirect(controller: "homePage", action: "index")
        }

        if (params.query == "*") {
            flash.message = "please provie a bit more than just a * for a query, you could query by name for example?"
            redirect(controller: "homePage", action: "index")
        }

        if (!params.query?.trim()) {
            return [:]
        }
        try {

            if (params?.format && params.format != "html") //Export
            {

                println "======== In Upload =============";
                params.put("offset", 0);
                params.put("max", Long.parseLong("0" + params.total.toString()));

                def result = searchService.textSearch(params.query.trim(), params)

                dataExportService.exportTextSearch(result, response, params)

            } else {

                if (params.offset == null || params.offset.toString().equals("0")) {
                    params.put("offset", 0);
                } else {
                    params.put("offset", Long.parseLong("0" + params.offset.toString()));
                }

                if (params.max == null || params.max.toString().equals("0")) {
                    params.put("max", 10);
                } else {
                    params.put("max", Long.parseLong("0" + params.max.toString()));
                }

                def result = searchService.textSearch(params.query.trim(), params)

                log.info("Result is: ${result}")
                return [searchResult: result]
            }

        } catch (SearchEngineQueryParseException ex) {
            return [parseException: true]
        }
        catch (BooleanQuery.TooManyClauses e) {

            flash.message = "please redesign you query, it returns to many results, ($params.query)!"
            redirect(action: "index", params: [query: params.query])
        }
    }
}
